import axios from 'axios'
import Messager from './messager';
import pinia from '@/store'
import useUser from '@/store/user'
import useMenuStore from '@/store/menu'
import useTagsViewStore from '@/store/tagsView'
import router,{resetRouter} from '@/router'



const instance = axios.create({
    baseURL: 'http://119.23.61.24/api',
    // timeout: -1
})

instance.interceptors.request.use((config) => {
    // debugger
    let userStore = useUser()
    if (userStore.token) {
        // console.log('userStore.token', userStore.token);
        config.headers['Authorization'] = userStore.token
    }
    return config;
})

instance.interceptors.response.use(
    response => {
        // console.log(response, 'response', router)
        if (response.data.code == 401001 || response.data.code == 401002 || response.data.code == 401003) {
            console.log('请重新登录');
            Messager.error(response.data.msg)
            let userStore = useUser()
            userStore.clearUserInfo()
            let menuStore = useMenuStore()
            menuStore.clearMenuRouterInfo()
            let tagsViewStore = useTagsViewStore()
            tagsViewStore.resetTagsView()
            setTimeout(() => {
                router.push('/login')
            }, 1000)
            return Promise.reject(new Error(response.data.msg))
        } else if (response.data.code == 0) {
            return Promise.resolve(response.data.data)
        } else {
            Messager.error(response.data.msg)
            return Promise.reject(new Error(response.data.msg))
        }
    },
    error => {
        Messager.error('服务器发生错误')
        // console.log(error);
        return Promise.reject(error)
    }
)

export default instance
